﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using System.Web.Script.Serialization;
using Newtonsoft.Json;

namespace Controllers
{
    public class FileController : BaseController
    {
        //分目录查找个人文档,共享文档,通知公告
        public ActionResult Find(int start, int limit, int fileClass, int? pid)
        {
            EmpBasicInfo ebi = Session["ebi"] as EmpBasicInfo;
            IQueryable<File> list;
            if (pid != null)//子目录
            {
                list = from r in ctx.Files where r.Pid == pid select r;
            }
            else if(fileClass==0)//个人文件
            {
                list = from r in ctx.Files where r.FileClass == 0 && r.Pid == null && r.OwnerId ==ebi.Id select r;
            }
            else if (fileClass == 1)//共享文件
            {
                list = from r in ctx.Files where r.FileClass == 1 && r.Pid==null select r;
            }
            else//通知公告
            {
                list = from r in ctx.Files where r.FileClass == 2 && (r.StatusId == 1 || r.OwnerId ==ebi.Id) select r;
            }
            //return Json(list);
            CJson CJson = new CJson();
            string json = CJson.ToJsonString("totalCount:" + list.Count() + ",data", list.OrderByDescending(r=>r.CreatTime).Skip(start).Take(limit).ToList());
            return Content(json);
        }

        //取最新的n条公告
        public ActionResult GetLatestNotices()
        {
            EmpBasicInfo ebi = Session["ebi"] as EmpBasicInfo;
            IEnumerable<File> list = ctx.ExecuteQuery<File>(string.Format(@"select top 6 a.Id,a.Pid,a.Name,a.Type,a.RealName,a.Size,a.CreatTime,a.OwnerId,a.FileClass,
a.OrderNo,a.LastUpdateTime,a.LastUpdaterId,
case when b.FileId is null and a.CreatTime>'2012-11-28' then 0 else {0} end as StatusId
from Files a left join (select distinct FileId from FileReadLog where ReaderId={0}) b on a.Id=b.FileId
where a.FileClass=2
order by a.CreatTime desc;",ebi.Id));
            return Json(list);
            //CJson CJson = new CJson();
            //string json = CJson.ToJsonString("totalCount:" + list.Count() + ",data", list.Take(8).ToList());
            //return Content(json);
        }

        //按登录用户查找授权文档
        public ActionResult GetAuthDoc(int start, int limit, int? fileId)
        {
            EmpBasicInfo ebi = Session["ebi"] as EmpBasicInfo;
            IQueryable<FileAuthed> v;
            if(fileId==null)
            {
                v = from f in ctx.Files
                    join af in ctx.FileAuths on f.Id equals af.FileId
                    where af.ToId == ebi.Id
                    orderby af.AuthDate descending
                    select new FileAuthed
                    {
                        Id = f.Id,
                        Pid = f.Pid,
                        Name = f.Name,
                        Type = f.Type,
                        RealName = f.RealName,
                        Size = f.Size,
                        CreatTime = af.AuthDate,
                        OwnerId = f.OwnerId,
                        LastUpdaterId = f.LastUpdaterId,
                        StatusId = f.StatusId,
                        FromId = af.FromId,
                        FromName = af.Employee.Name,
                        ToId = af.ToId,
                        AuthType = af.AuthType,
                        AuthLevel = af.AuthLevel
                    };
            }
            else
            {
                var pFile = ctx.FileAuths.Single(r => r.FileId == fileId && r.ToId ==ebi.Id);//前期只考虑父子目录授权,祖孙授权暂不考虑
                v = from r in ctx.Files
                        where r.Pid == fileId
                        select new FileAuthed
                        {
                            Id = r.Id,
                            Pid = r.Pid,
                            Name = r.Name,
                            Type = r.Type,
                            RealName = r.RealName,
                            Size = r.Size,
                            CreatTime=r.CreatTime,
                            OwnerId = r.OwnerId,
                            LastUpdaterId = r.LastUpdaterId,
                            StatusId = r.StatusId,
                            FromId = pFile.FromId,
                            ToId = pFile.ToId,
                            AuthType = pFile.AuthType,
                            AuthLevel = pFile.AuthLevel
                        };
            }
            string json;
            CJson CJson = new CJson();
            json = CJson.ToJsonString("totalCount:" + v.Count() + ",data", v.OrderByDescending(r=>r.CreatTime).Skip(start).Take(limit).ToList());
            return Content(json);
        }

        //按文档Id查找已授权用户
        public ActionResult GetAuthedEmp(int fileId)
        {
            var v = from r in ctx.FileAuths
                    join e in ctx.Employees on r.ToId equals e.Id
                    where r.FileId == fileId
                    select new EmpAuthed
                    {
                        Id = r.Id,
                        FileId = r.FileId,
                        FromId = r.FromId,
                        ToId = r.ToId,
                        AuthType = r.AuthType,
                        AuthLevel = r.AuthLevel==1,
                        AuthDate = r.AuthDate,
                        Name = e.Name
                    };
            return Json(v);
        }

        //文档授权
        public ActionResult AuthOpt(int fileId, string empIds, string empIds2)
        {
            string retStr = "Succeed";
            IQueryable<FileAuth> qs= ctx.FileAuths.Where(r => r.FileId == fileId);
            IList<FileAuth> authedList = qs.ToList();
            EmpBasicInfo ebi = Session["ebi"] as EmpBasicInfo;
            string empId = ebi.Id.ToString();
            StringBuilder sb = new StringBuilder();
            if(!string.IsNullOrEmpty(empIds))
            {
                string[] a = empIds.Split(',');
                foreach (string s in a)
                {
                    if (authedList.Where(r => r.ToId == int.Parse(s)).Count() == 0)
                    {
                        sb.AppendFormat(@"insert into FileAuth(FileId,FromId,ToId,AuthType) values({0},{1},{2},0);",fileId, empId, s);
                    }
                }
            }
            if (!string.IsNullOrEmpty(empIds2))
            {
                string[] a2 = empIds2.Split(',');
                foreach (string s in a2)
                {
                    if (authedList.Where(r => r.ToId == int.Parse(s)).Count() == 0)
                    {
                        sb.AppendFormat(@"insert into FileAuth(FileId,FromId,ToId,AuthType) values({0},{1},{2},1);", fileId, empId, s);
                    }
                }
            }
            StringBuilder sb2 = new StringBuilder();
            foreach(FileAuth fa in authedList)
            {
                if(empIds.IndexOf(fa.ToId.ToString())<0 &&empIds2.IndexOf(fa.ToId.ToString())<0)
                {
                    sb2.Append(","+fa.Id);
                }
            }
            if(sb2.Length>0)
            {
                sb.AppendFormat(@"delete from FileAuth where Id in({0}) and FromId={1};", sb2.ToString().Trim(','),ebi.Id);
            }
            if(sb.Length!=0)
            {
                try
                {
                    ctx.ExecuteCommand(sb.ToString());
                }
                catch (Exception ex)
                {
                    retStr = ex.Message;
                }
            }
            return Json(retStr);
        }

        //新建文件夹
        public string NewFolder(int fileClass, int? pid,string folderName)
        {
            string retStr = "Succeed";
            try
            {
                File file = new File();
                file.Name = folderName;
                file.FileClass = fileClass;
                EmpBasicInfo ebi = Session["ebi"] as EmpBasicInfo;
                file.OwnerId = ebi.Id;
                if (!string.IsNullOrEmpty(Request.Form["pid"]))
                {
                    file.Pid = int.Parse(Request.Form["pid"]);
                }
                //file.RealName = folderName;
                file.Type ="dir";
                file.CreatTime = DateTime.Now;
                ctx.Files.InsertOnSubmit(file);
                ctx.SubmitChanges();
            }
            catch (Exception ex)
            {
                retStr = ex.Message;
            }
            return retStr;
        }

        //上传文件,写数据库.注意:因上传文件使用的是form,故不能回传数据,否则会刷新页面
        public ActionResult FileUpload(FormCollection collection)
        {
            var rdto = new ResultMessages();
            rdto.Result = true;
            var f = Request.Files[0];
            if (f != null && f.ContentLength > 0)
            {
                string destination;
                switch (Request.Form["fileClass"])
                {
                    case "0": destination = Server.MapPath("/PersonalFolder/");
                        break;
                    case "1": destination = Server.MapPath("/ShareFolder/");
                        break;
                    case "2": destination = Server.MapPath("/NoticeFolder/");
                        break;
                    default: destination = Server.MapPath("/PersonalFolder/");
                        break;
                }

                string filename;
                if (!string.IsNullOrEmpty(Request.Form["docTitle"]))
                {
                    filename = Server.UrlDecode(Request.Form["docTitle"]) + "." + Request.Form["docType"];//编码转换,解决乱码问题
                }
                else
                {
                    filename = f.FileName;
                    filename = filename.Substring(filename.LastIndexOf(@"\")+1);
                }
                string newFileName =DateTime.Now.ToString("yyyyMMddhhmmss") + filename.Substring(filename.LastIndexOf("."));
                try
                {
                    File file = new File();
                    file.FileClass = int.Parse(Request.Form["fileClass"]);
                    if (!string.IsNullOrEmpty(Request.Form["docID"]))
                    {
                        file = ctx.Files.Single(r => r.Id == int.Parse(Request.Form["docID"]));
                        file.LastUpdateTime = DateTime.Now;
                        EmpBasicInfo ebi = Session["ebi"] as EmpBasicInfo;
                        file.LastUpdaterId = ebi.Id;
                    }
                    else
                    {
                        EmpBasicInfo ebi = Session["ebi"] as EmpBasicInfo;
                        file.OwnerId = ebi.Id;
                        if (!string.IsNullOrEmpty(Request.Form["pid"]))
                        {
                            file.Pid = int.Parse(Request.Form["pid"]);
                        }
                        file.RealName = newFileName;
                        file.Type = filename.Substring(filename.LastIndexOf(".") + 1);
                        file.CreatTime = DateTime.Now;
                        ctx.Files.InsertOnSubmit(file);
                    }
                    file.Name = filename.Substring(0, filename.LastIndexOf("."));
                    file.Size = f.ContentLength;
                    file.StatusId = 0;
                    if (!string.IsNullOrEmpty(Request.Form["statusId"]))
                    {
                        file.StatusId = int.Parse(Request.Form["statusId"]);
                    }

                    f.SaveAs(destination + file.RealName);
                    //写数据库
                    ctx.SubmitChanges();
                }
                catch (Exception ex)
                {
                    rdto.Result = false;
                    rdto.Message = ex.Message;
                }
            }
            //JavaScriptSerializer jss = new JavaScriptSerializer();
            //Response.Write(jss.Serialize(rdto));
            Response.Write("{success:'true',fn:'noMatter'}");
            return null;
        }

        //获得当前目录的父目录Id
        public ActionResult GetParentId(int? currId)
        {
            var rdto = new ResultMessages();
            rdto.Result = true;
            int? pId = null;
            if(currId!=null)
            {
                pId =ctx.Files.Single(r => r.Id == currId).Pid;
            }
            rdto.Data = pId;
            return Json(rdto);
        }

        //获得当前目录的授权上级目录Id
        public ActionResult GetAuthParentId(int? currId)
        {
            var rdto = new ResultMessages();
            rdto.Result = true;
            int? pId = null;
            if (currId != null)
            {
                string strSql = @"declare @pId int,@cnt int,@parentId int;
                                select @pId=pid from Files where Id={0};
                                if(@pId is not null)
                                begin
	                                with t as(
		                                SELECT Id,Pid,Name,Type,RealName,Size,CreatTime,OwnerId,
			                                OrderNo,LastUpdateTime,LastUpdaterId,StatusId
	                                    FROM Files f1 where Id=@pId
	                                    union all
	                                    select f2.* from Files f2,t where f2.Id=t.Pid)
	                                select @cnt=COUNT(0)
	                                from t inner join FileAuth fa on t.Id=fa.FileId where fa.ToId={1};
	                                if(@cnt>0)
		                                select @parentId=@pId;
                                end
                                select @parentId pId;";
                EmpBasicInfo ebi = Session["ebi"] as EmpBasicInfo;
                var v = ctx.ExecuteQuery<int?>(strSql, currId, ebi.Id);
                pId = v.First();
            }
            rdto.Data = pId;
            return Json(rdto);
        }

        //文档访问日志,写数据库
        public ActionResult AccessLog(int fileId)
        {
            EmpBasicInfo ebi = Session["ebi"] as EmpBasicInfo;
            ResultMessages rdto=new ResultMessages();
            rdto.Result = true;
            var v = new FileReadLog();
            v.FileId = fileId;
            v.ReaderId = ebi.Id;
            v.ActionId = 0;
            v.ReadDate = DateTime.Now;
            ctx.FileReadLogs.InsertOnSubmit(v);
            ctx.SubmitChanges();
            return Json(rdto);
        }

        //文档访问日志,读数据库
        public IQueryable<FileReadLogDTO> FileReadLog(int fileId)
        {
            IQueryable<FileReadLogDTO> list = from r in ctx.FileReadLogs
                                              where r.FileId == fileId
                                              orderby r.ReadDate descending 
                                              select
                                                  new FileReadLogDTO
                                                      {
                                                          Reader = r.Employee.Name,
                                                          ReadTime = r.ReadDate,
                                                          ActionId = r.ActionId
                                                      };
            return list;
        }

        //取消文件签出状态
        public ActionResult AccessCancel(int fileId)
        {
            File file = ctx.Files.Single(r=>r.Id==fileId);
            file.StatusId = 0;
            ctx.SubmitChanges();
            return null;
        }

        //获取可编辑文档的写权限
        public ActionResult ObtainWritable(int fileId)
        {
            var rdto = new ResultMessages();
            var v = ctx.Files.Single(r => r.Id == fileId);
            if(v.StatusId==0)//未签出,改签出状态,写访问日志
            {
                EmpBasicInfo ebi = Session["ebi"] as EmpBasicInfo;
                v.LastUpdaterId = ebi.Id;
                v.LastUpdateTime = DateTime.Now;
                v.StatusId = 1;

                var fLog = new FileReadLog();
                fLog.FileId = fileId;
                fLog.ReaderId = ebi.Id;
                fLog.ActionId =1;
                fLog.ReadDate = DateTime.Now;
                ctx.FileReadLogs.InsertOnSubmit(fLog);

                ctx.SubmitChanges();
                rdto.Result = true;
            }
            else//已签出,返回被谁签出
            {
                rdto.Result = false;
                var e = ctx.Employees.Single(r => r.Id == v.LastUpdaterId);
                rdto.Data = e.Id;
                rdto.Message =e.Name;
            }
            return Json(rdto);
        }

        //删除文档,调用递归函数
        public string Delete(string strFolderID)
        {
            string retStr = "Succeed";
            try
            {
                foreach (string s in strFolderID.Split(','))
                {
                    delRecursion(int.Parse(s));
                }
            }
            catch(Exception ex)
            {
                retStr = ex.Message;
            }
            return retStr;
        }
        //递归删除文档
        private void delRecursion(int fileId)
        {
            var v = from r in ctx.Files where r.Pid == fileId select r;
            if(v.Count()>0)
            {
                foreach(var v0 in v)
                {
                    delRecursion(v0.Id);
                }
            }
            var f = ctx.Files.Single(r => r.Id == fileId);
            if(f.Type!="dir")
            {
                //删除硬盘上文件
                string delFile = Server.MapPath("~") + "\\PersonalFolder\\" + f.RealName;
                if(f.FileClass==1)
                {
                    delFile = Server.MapPath("~") + "\\ShareFolder\\" + f.RealName;
                }
                else if (f.FileClass == 2)
                {
                    delFile = Server.MapPath("~") + "\\NoticeFolder\\" + f.RealName;
                }
                if(System.IO.File.Exists(delFile))
                {
                    System.IO.File.Delete(delFile);
                }
            }

            var fLogs = from r in ctx.FileReadLogs where r.FileId == fileId select r;
            ctx.FileReadLogs.DeleteAllOnSubmit(fLogs);//删除日志
            var fAuthed = from r in ctx.FileAuths where r.FileId == fileId select r;
            ctx.FileAuths.DeleteAllOnSubmit(fAuthed);//删除授权
            ctx.Files.DeleteOnSubmit(f);//删除文件

            ctx.SubmitChanges();
        }

        //按登录人员获取未读文件
        public ActionResult GetUnReaded()
        {
            EmpBasicInfo ebi = Session["ebi"] as EmpBasicInfo;
            var list = from r in ctx.FileAuths join r2 in ctx.Files on r.FileId equals r2.Id
                    where
                        r.ToId == ebi.Id &&r2.CreatTime>DateTime.Now.AddMonths(-1)&&
                        !(from r3 in ctx.FileReadLogs where r3.ReaderId==ebi.Id select r3.FileId).Contains(r.FileId)
                        orderby r.AuthDate descending
                    select new{r2.Id,r2.Name,r2.Type,r2.RealName,r2.OwnerId,r2.Pid,r.AuthDate,r.AuthLevel,OriAuthor=r2.Employee.Name,From=r.Employee.Name};
            return Json(list);
        }

        //打包下载全部文件
        public ActionResult GetFileAll()
        {
            var rdto = new ResultMessages();
            rdto.Result = true;
            EmpBasicInfo ebi = Session["ebi"] as EmpBasicInfo;
            string destination = Server.MapPath("/PersonalFolder/" + ebi.Name);
            string destinationRar = Server.MapPath("/PersonalFolder/Rar/" + ebi.Name+".rar");
            deleteFolder(destination); //递归删除文件夹
            if (System.IO.File.Exists(destinationRar))
            {
                System.IO.File.Delete(destinationRar);
            }
            System.IO.Directory.CreateDirectory(destination);

            IQueryable<File> list = from r in ctx.Files where r.FileClass == 0 && r.OwnerId == ebi.Id && r.Pid==null select r;
            foreach(var f in list)
            {
                if(f.Type=="dir")
                {
                    string vDir = "/PersonalFolder/" + ebi.Name + "/" + f.Name;
                    string dir = Server.MapPath(vDir);
                    System.IO.Directory.CreateDirectory(dir);
                    copyFolder(f.Id, vDir);
                }
                else
                {
                    string orignFile = Server.MapPath("/PersonalFolder/" + f.RealName);
                    string newFile = Server.MapPath("/PersonalFolder/" + ebi.Name + "/" + f.Name + "." + f.Type);
                    if (System.IO.File.Exists(orignFile))
                    {
                        System.IO.File.Copy(orignFile, newFile, true);
                    }
                }
            }
            //压缩文件
            string dRar = Server.MapPath("/PersonalFolder/Rar/" + ebi.Name);
            string rar = " a -ep1 -r " + dRar + " " + destination;
            ProcessStartInfo startInfo = new ProcessStartInfo(@"C:\Program Files\WinRAR\Rar.exe", rar);
            startInfo.WindowStyle = ProcessWindowStyle.Hidden;
            System.Diagnostics.Process a = new Process();
            try
            {
                a.StartInfo = startInfo;
                a.Start();
                a.WaitForExit();
            }
            catch (Exception ex)
            {
                rdto.Result = false;
                rdto.Message = ex.Message;
            }
            //deleteFolder(destination); //递归删除文件夹
            return Json(rdto);
        }
        //打包下载选中的文件
        public string GetFileChoosed(string strFolderID)
        {
            string retStr;
            string[] idsStr = strFolderID.Split(',');
            int[] ids =new int[idsStr.Length];
            int i = 0;
            foreach(string id in strFolderID.Split(','))
            {
                ids[i++]=int.Parse(id);
            }
            IEnumerable<File> list =(from r in ctx.Files where ids.Contains(r.Id) select r).ToList();
            string sourceFolder;
            if(list.First().FileClass==1)
            {
                sourceFolder = Server.MapPath("/ShareFolder");
            }
            else if (list.First().FileClass == 2)
            {
                sourceFolder = Server.MapPath("/NoticeFolder");
            }
            else
            {
                sourceFolder = Server.MapPath("/PersonalFolder");
            }
            string newFileName = DateTime.Now.ToString("yyyyMMddHHmmss");
            string destinationFolder ="/TempFile/" + newFileName;
            string destinationRar ="/TempFile/" + newFileName + ".rar";
            string destinationFolderPath = Server.MapPath(destinationFolder);
            string destinationRarPath = Server.MapPath(destinationRar);
            deleteFolder(destinationFolderPath); //递归删除文件夹
            if (System.IO.File.Exists(destinationRarPath))
            {
                System.IO.File.Delete(destinationRarPath);
            }
            Directory.CreateDirectory(destinationFolderPath);

            foreach (var f in list)
            {
                if (f.Type == "dir")
                {
                    string vDir = destinationFolder +"/" + f.Name;
                    string dir = Server.MapPath(vDir);
                    Directory.CreateDirectory(dir);
                    copyFolder(f.Id, vDir);
                }
                else
                {
                    string orignFile =sourceFolder+"/" + f.RealName;
                    string newFile =destinationFolderPath + "/" + f.Name + "." + f.Type;
                    if (System.IO.File.Exists(orignFile))
                    {
                        System.IO.File.Copy(orignFile, newFile, true);
                    }
                }
            }
            //压缩文件
            string rar = " a -ep1 -r " + destinationRarPath + " " + destinationFolderPath;
            ProcessStartInfo startInfo = new ProcessStartInfo(@"C:\Program Files\WinRAR\Rar.exe", rar);
            startInfo.WindowStyle = ProcessWindowStyle.Hidden;
            Process a = new Process();
            try
            {
                a.StartInfo = startInfo;
                a.Start();
                a.WaitForExit();
                retStr =newFileName + ".rar";
            }
            catch (Exception ex)
            {
                retStr = ex.Message;
            }
            //deleteFolder(destination); //递归删除文件夹
            return retStr;
        }
        //递归删除文件夹及文件
        private void deleteFolder(string dir)
        {
            if (Directory.Exists(dir)) //如果存在这个文件夹删除之
            {
                foreach (string d in Directory.GetFileSystemEntries(dir))
                {
                    if (System.IO.File.Exists(d))
                        System.IO.File.Delete(d); //直接删除其中的文件
                    else
                        deleteFolder(d); //递归删除子文件夹
                }
                Directory.Delete(dir); //删除已空文件夹
            }
        }
        //递归复制文件夹及文件
        private void copyFolder(int pId,string dDir)
        {
            IQueryable<File> list = from r in ctx.Files where r.Pid == pId select r;
            string sourceFolder;
            if (list.First().FileClass == 1)
            {
                sourceFolder = Server.MapPath("/ShareFolder");
            }
            else if (list.First().FileClass == 2)
            {
                sourceFolder = Server.MapPath("/NoticeFolder");
            }
            else
            {
                sourceFolder = Server.MapPath("/PersonalFolder");
            }
            foreach (var f in list)
            {
                if (f.Type == "dir")
                {
                    string dir = Server.MapPath(dDir+"/" + f.Name);
                    Directory.CreateDirectory(dir);
                    copyFolder(f.Id, dir);
                }
                else
                {
                    string orignFile = Server.MapPath(sourceFolder+"/" + f.RealName);
                    string newFile = Server.MapPath(dDir + "/" + f.Name + "." + f.Type);
                    if (System.IO.File.Exists(orignFile))
                    {
                        System.IO.File.Copy(orignFile, newFile, true);
                    }
                }
            }
        }

        //清理 2月 之前的个人文件
        public void DelFile(int id)
        {
            IQueryable<File> list = from r in ctx.Files where r.Type != "dir" && r.CreatTime <DateTime.Today.AddDays(id) && r.FileClass==0 select r;
            foreach (File f in list)
            {
                IQueryable<FileAuth> fa = from r in ctx.FileAuths where r.FileId == f.Id select r;
                ctx.FileAuths.DeleteAllOnSubmit(fa);
                IQueryable<FileReadLog> frl = from r in ctx.FileReadLogs where r.FileId == f.Id select r;
                ctx.FileReadLogs.DeleteAllOnSubmit(frl);
                ctx.Files.DeleteOnSubmit(f);

                string destination = Server.MapPath("/PersonalFolder/" +f.RealName);
                if (System.IO.File.Exists(destination))
                    System.IO.File.Delete(destination); //直接删除其中的文件
            }
            ctx.SubmitChanges();
        }
        //清理 离职员工的个人文件
        public void DelFileExpire()
        {
            IQueryable<File> list = from r in ctx.Files where r.Type != "dir" && (from e in ctx.Employees where e.LeaveDate != null&&e.LeaveDate<DateTime.Now select e.Id).Contains(r.OwnerId) && r.FileClass == 0 select r;
            foreach (File f in list)
            {
                IQueryable<FileAuth> fa = from r in ctx.FileAuths where r.FileId == f.Id select r;
                ctx.FileAuths.DeleteAllOnSubmit(fa);
                IQueryable<FileReadLog> frl = from r in ctx.FileReadLogs where r.FileId == f.Id select r;
                ctx.FileReadLogs.DeleteAllOnSubmit(frl);
                ctx.Files.DeleteOnSubmit(f);

                string destination = Server.MapPath("/PersonalFolder/" + f.RealName);
                if (System.IO.File.Exists(destination))
                    System.IO.File.Delete(destination); //直接删除其中的文件
            }
            ctx.SubmitChanges();
        }

        //按Id查找File对象
        public File GetFile(int fileId)
        {
            File f = ctx.Files.SingleOrDefault(r => r.Id == fileId);
            return f;
        }

        //按部门Id 和 职位Id 获取员工
        public ActionResult GetUnauthedEmp(int deptId, string posId)
        {
            IEnumerable<EmpBasicInfo> list;
            if(string.IsNullOrEmpty(posId))
            {
                string strSql = @"with t as(select Id,Text from Depts where Id={0}
  union all
  select a.Id,a.Text from Depts a,t where a.Pid=t.Id)
select Id,Name from(SELECT a.Id,Name,MIN(b.PosId)PosId FROM Employee a,EmpDepPositions b
  where LeaveDate is null
  and a.Id in(select EmpId from EmpDepPositions where DeptId in(select Id from t))
  and a.Id=b.EmpId group by a.Id,Name)t2 order by PosId,Id;";
                list = ctx.ExecuteQuery<EmpBasicInfo>(strSql, deptId);
            }
            else
            {
                string strSql = @"with t as(select Id,Text from Depts where Id={0}
  union all
  select a.Id,a.Text from Depts a,t where a.Pid=t.Id)
SELECT a.Id,Name FROM Employee a,EmpDepPositions b
  where LeaveDate is null
  and a.Id in(select EmpId from EmpDepPositions where DeptId in(select Id from t))
  and a.Id=b.EmpId and b.PosId={1} order by b.PosId,a.Id;";
                list = ctx.ExecuteQuery<EmpBasicInfo>(strSql, deptId,int.Parse(posId));
            }
            return Json(list);
        }

        //文件重命名
        public string Rename(int fileId,string name)
        {
            string retStr = "Succeed";
            var v = ctx.Files.Single(r => r.Id == fileId);
            v.Name = name;
            ctx.SubmitChanges();
            return retStr;
        }

        //文件排序
        public string AdjustOrder(string strFolderID)
        {
            string retStr = "Succeed";
            int i = 0;
            foreach (string s in strFolderID.Split(','))
            {
                var v = ctx.Files.Single(r => r.Id ==int.Parse(s));
                v.OrderNo = i++;
            }
            ctx.SubmitChanges();
            return retStr;
        }
    }
}